package com.lagou.edu.mvcframework.interceptor;

import com.lagou.edu.mvcframework.annotations.Security;
import com.lagou.edu.mvcframework.pojo.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class SecurityInterceptor {

    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws IOException {
        boolean allowed = false;

        String username = req.getParameter("username");

        Handler h = (Handler)handler;
        Class<?> controllerClass = h.getController().getClass();
        boolean controllerClassAnnotationPresent = controllerClass.isAnnotationPresent(Security.class);
        Method method = h.getMethod();
        boolean methodAnnotationPresent = method.isAnnotationPresent(Security.class);
        //没有security注解，任何人都能请求
        if (!controllerClassAnnotationPresent && !methodAnnotationPresent) {
            allowed = true;
        }

        if (controllerClassAnnotationPresent) {
            allowed = checkUser(controllerClass.getAnnotation(Security.class), username);
        }

        if (methodAnnotationPresent) {
            allowed = checkUser(method.getAnnotation(Security.class), username);
        }

        if (!allowed) {
            resp.getWriter().write("Permission Denied");
        }
        return allowed;
    }

    private boolean checkUser(Security security, String target) {
        String[] value = security.value();
        for (String s : value) {
            if (s.equals(target)) {
                return true;
            }
        }
        return false;
    }
}
